package com.suyl.tools.proxy.core.filter;

import com.suyl.tools.proxy.core.config.HttpProxyContext;
import org.apache.http.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author suyanlong
 * @Date 2020/6/14 16:38
 * @Version 1.0
 * @Description 代理转发
 */
@WebFilter(filterName = "ProxyFilter", urlPatterns = "/web/proxy/*")
public class ProxyFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(ProxyFilter.class);

    @Autowired
    HttpClient httpClient;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("ProxyFilter init......");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        String method = request.getMethod();
        // 配置容器
        HttpProxyContext.add("/web/proxy/suyl", "suyl");
        HttpProxyContext.add("/web/proxy/candy", "candy");
        HttpProxyContext.add("/web/proxy/sohikoryuu", "sohikoryuu");
        if (HttpProxyContext.containsKey(uri)) {
            long start = System.currentTimeMillis();
            String url = HttpProxyContext.get(request.getRequestURI());
            Map<String, String> postParams = null;
            String queryString = request.getQueryString();
//            判断 请求类型处理参数
            if ("GET".equalsIgnoreCase(method)) {
                if (StringUtils.isEmpty(queryString)) {
//                    url = url + "?" + queryString;
                }
            } else if ("POST".equalsIgnoreCase(method)) {
        //                postParams = doParseParams(request);
            }
            // 执行真正的代理路径请求
            //            String result = httpClient.execute(method, url, postParams);
            long end = System.currentTimeMillis();
            if (logger.isDebugEnabled()) {
                logger.debug("RemoteAddr:" + request.getRemoteAddr() + ", " + "RequestURI:" + request.getRequestURI() + ", cost time:" + (start - end) + "ms");
            }
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // 输出代理结果
            response.getWriter().print(url);
            return;
        }
        filterChain.doFilter(request, response);//执行请求
    }

    @Override
    public void destroy() {
        logger.info("ProxyFilter destroy......");
    }


    private Map<String, String> doParseParams(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length > 0) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        String paramsLog = "";
        Set<Map.Entry<String, String>> set = map.entrySet();
        for (Map.Entry entry : set) {
            paramsLog = paramsLog + " " + entry.getKey() + ":" + entry.getValue() + ",";
        }
        if (paramsLog.endsWith(",")) {
            paramsLog = paramsLog.substring(0, paramsLog.lastIndexOf(","));
        }
        logger.info("RemoteAddr:" + request.getRemoteAddr() + ", " + "RequestURI:" + request.getRequestURI() + ", Params=[" + paramsLog + "]");
        return map;
    }
}
